package com.pomr.controller.record;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.pomr.model.health.FriendTel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.client.OkHttpClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pomr.model.form.RecordSelect;
import com.pomr.model.health.PersonRecord;
import com.pomr.model.menu.Sex;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.City;
import com.pomr.model.sys.Coutry;
import com.pomr.model.sys.Province;
import com.pomr.model.sys.User;
import com.pomr.service.sys.PersonRecordService;
import com.pomr.service.sys.UserService;
import com.pomr.util.common.CommonData;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
import com.pomr.util.page.PageManager;
import com.pomr.util.page.PageParam;
/**
 * 个人档案管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/person")
public class PersonRecordController {
	@Autowired
	@Qualifier("personRecordServiceImpl")
	private PersonRecordService personRecordService;
	@Autowired
	@Qualifier("userServiceImpl")
	private UserService userService;
	
	/**
	 * 进入档案首页
	 * @return
	 */
	@RequestMapping(value="/first",method=RequestMethod.GET)
	public String manager(){
		return "sys/person/person";
	}
	/**
	 * 添加个人档案 获取初始化信息
	 * @return
	 */
	@RequestMapping(value="/inter-insert",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData insert(){
		ResponseData pd = null;
		try {
			pd = ResponseData.ok();
			pd.putDataValue("Sex", CommonData.data.get("Sex"));
			pd.putDataValue("Marriage", CommonData.data.get("Marriage"));
			pd.putDataValue("HealthCondition", CommonData.data.get("HealthCondition"));
			pd.putDataValue("Industry", CommonData.data.get("Industry"));
			pd.putDataValue("Province", CommonData.data.get("Province"));
			pd.putDataValue("City", CommonData.data.get("City"));
			pd.putDataValue("Coutry", CommonData.data.get("Coutry"));
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	/**
	 * 添加个人档案
	 * @return
	 */
	@RequestMapping(value="/inter-insert",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData insert(@RequestBody PersonRecord record,HttpServletRequest request){
		ResponseData pd = null;
		try {
			//添加创建时间 创建人 创建机构
			User user = JWT.findUserByToken(request);
			record.setUser(user);
			record.setAgency(user.getAgency());
			record.setCreateTime(new Date());
			if(personRecordService.insertRecord(record)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	
	@RequestMapping(value="/inter-valididcard",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData valididcard(@RequestBody Map<String, String> map,HttpServletRequest request){
		ResponseData pd = null;
		try {
			if(!personRecordService.searchPersonRecordByIdcard(map.get("idcard"))){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.custom("已存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 查询个人档案 获取初始化信息
	 * @return
	 */
	@RequestMapping(value="/inter-select",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData select(HttpServletRequest request){
		ResponseData pd = null;
		try {
			pd = ResponseData.ok();
			pd.putDataValue("Sex", CommonData.data.get("Sex"));
			pd.putDataValue("HealthCondition", CommonData.data.get("HealthCondition"));
			User user = JWT.findUserByToken(request);
			List<Agency> agencys = userService.findAgencysWithUser(user);
			pd.putDataValue("agencys", agencys);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	
	@RequestMapping(value="/inter-searchbefore",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchPersonBefore(HttpServletRequest request,PageParam param){
		Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
		try {
			String page = param.getPage();
			String limit = param.getLimit();
			Map<String, String> map = param.getParams();
			String name = map.get("name")==null?"":map.get("name").toString();
			String idcard = map.get("idcard")==null?"":map.get("idcard").toString();
			String status = map.get("status")==null?"":map.get("status").toString();
			RecordSelect ps = new RecordSelect();
			ps.setName(name);
			ps.setIdcard(idcard);
			ps.setStatus(status);
			p.setCunrrentPage(Integer.valueOf(page));
			p.setPageSize(Integer.valueOf(limit));
			p = personRecordService.selectRecords(ps,p);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return p;
	}
	
	/**
	 * 个人档案查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-selectlist",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> selectList(HttpServletRequest request){
		try {
			String page = request.getParameter("cunrrentPage");
			String psize = request.getParameter("pageSize");
			String selectstr = request.getParameter("djson");
			Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
			p.setCunrrentPage(Integer.valueOf(page));
			p.setPageSize(Integer.valueOf(psize));
			RecordSelect select = JSONObject.parseObject(selectstr, RecordSelect.class);
			p = personRecordService.selectRecords(select, p);
			System.out.println(p.getRows().size());
			System.out.println(JSON.toJSONString(p));
			return p;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 删除某个个人档案
	 * @return
	 */
	@RequestMapping(value="/inter-delete",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData delete(@RequestBody Map<String, Object> map){
		Integer id = (Integer) map.get("id");
		System.out.println(id);
		PersonRecord record = new PersonRecord();
		record.setId(id);
		ResponseData pd = null;
		if(record.getId()<=0 && (record.getIdcard()==null || "".equals(record.getIdcard()))){//如果主键跟身份证号都不存在，无法删除
			pd = ResponseData.badRequest();
		}else{
			try {
				if(personRecordService.deleteRecord(record)){
					pd = ResponseData.ok();
				}else{
					pd = ResponseData.fail();
				}
			} catch (Exception e) {
				e.printStackTrace();
				pd = ResponseData.exceptionError();
			}
		}
		
		return pd;
	}
	
	/**
	 * 更新某个个人档案
	 * @param record
	 * @return
	 */
	@RequestMapping(value="/inter-update",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData update(@RequestBody PersonRecord record){
		ResponseData pd = null;
		if(record.getId()<=0 && (record.getIdcard()==null || "".equals(record.getIdcard()))){//如果主键跟身份证号都不存在，无法删除
			pd = ResponseData.badRequest();
		}else{
			try {
				if(personRecordService.updateRecord(record)){
					pd = ResponseData.ok();
				}else{
					pd = ResponseData.fail();
				}
			} catch (Exception e) {
				e.printStackTrace();
				pd = ResponseData.exceptionError();
			}
		}
		return pd;
	}
	
	/**
	 * 通过主键或身份证号查询某一个人概要信息
	 * @param map  id:档案主键   idcard:身份证号
	 * @return
	 */
	@RequestMapping(value="/inter-select",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData select(@RequestBody  Map<String, Object> map){
		ResponseData pd = null;
			try {
				Object idobj = map.get("id");
				Object idcardobj = map.get("idcard");
				Integer id = null;
				String idcard = null;
				if(idobj != null){
					id = (Integer) idobj;
				}
				if(idcardobj != null){
					idcard = idcardobj.toString();
				}
				PersonRecord record = new PersonRecord();
				record.setId(id);
				record.setIdcard(idcard);
				record = personRecordService.selectRecord(record);
				if(record == null){
					pd = ResponseData.notFound();
				}else{
					pd = ResponseData.ok();
					pd.putDataValue("record", record);
					Map<String, Object> commonmap = CommonData.data;
					pd.putDataValue("Sex", commonmap.get("Sex"));
					pd.putDataValue("Marriage", commonmap.get("Marriage"));
					pd.putDataValue("HealthCondition", commonmap.get("HealthCondition"));
					pd.putDataValue("Industry", commonmap.get("Industry"));
					//获取全部省份
					record.getCoutry().getCity().getProvince().setId(record.getCoutry().getCity().getProvince().getId());
					List<Province> ps = (List<Province>) commonmap.get("Province");
					pd.putDataValue("Province", ps);
					//获取当前省下市
					List<City> cs = (List<City>) commonmap.get("City");
					List<City> citys = new ArrayList<City>();
					for(City c:cs){
						if(c.getProvince().getId().equals(record.getCoutry().getCity().getProvince().getId())){
							citys.add(c);
						}
					}
					System.out.println(citys.size());
					pd.putDataValue("City", citys);
					//获取当前市下县
					record.getCoutry().getCity().setId(record.getCoutry().getCity().getId());
					List<Coutry> cts = (List<Coutry>) commonmap.get("Coutry");
					List<Coutry> coutrys = new ArrayList<Coutry>();
					for(Coutry c:cts){
						if(c.getCity().getId().equals(record.getCoutry().getCity().getId())){
							coutrys.add(c);
						}
					}
					System.out.println(coutrys.size());
					pd.putDataValue("Coutry", coutrys);
				}
			} catch (Exception e) {
				e.printStackTrace();
				pd = ResponseData.exceptionError();
			}
		return pd;
		
		
	}
	
//	/**
//	 * 根据条件查询个人档案列表
//	 * @return
//	 */
//	@RequestMapping(value="/inter/selectByConditions",method=RequestMethod.POST)
//	@ResponseBody
//	public PageManager<List<PersonRecord>> selectByConditions(@RequestBody PersonRecord record,String pageSize,HttpServletRequest request){
//		System.out.println(pageSize);
//		System.out.println(request.getParameter("cp")+"---");
//		try {
//			Page<PersonRecord> p = personRecordService.selectByConditions();
//			PageManager<List<PersonRecord>> pm = new PageManager<List<PersonRecord>>();
//			System.out.println(p.getRows().size());
//			pm.setTotal(2);
//			List<PersonRecord> i = p.getRows();
//			i.remove(0);
//			pm.setRows(i);
//			pm.setPage(p.getCunrrentPage());
//			return pm;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
	
	/**
	 * 批量删除
	 * @return
	 */
	@RequestMapping(value="/inter-deletelist",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData deleteList(@RequestBody Map<String,Object> map){
		ResponseData pd = null;
		try{
			String[] ids = map.get("id").toString().split(",");
			List<String> idsl = Arrays.asList(ids);
			if(personRecordService.deleteRecords(idsl)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		
		return pd;
	}
	
	/**
	 * 批量更新档案
	 * @return
	 */
	@RequestMapping(value="/inter-updatelist",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData updateRecords(@RequestBody List<PersonRecord> records){
		ResponseData pd = null;
		if(records!=null && records.size()>0){
			try {
				if(personRecordService.updateRecords(records)){
					pd = ResponseData.ok();
				}else{
					pd = ResponseData.fail();
				}
			} catch (Exception e) {
				e.printStackTrace();
				pd = ResponseData.exceptionError();
			}
		}else{
			pd = ResponseData.badRequest();
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-searchinfo",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editRecordBefore(@RequestBody PersonRecord record){
		ResponseData pd = null;
		try {
			record = personRecordService.selectRecord(record);
			if(record != null){
				Map<String, Object> commonmap = CommonData.data;
				pd = ResponseData.ok();
				pd.putDataValue("record", record);
				pd.putDataValue("Sex", commonmap.get("Sex"));
				pd.putDataValue("Marriage", commonmap.get("Marriage"));
				pd.putDataValue("HealthCondition", commonmap.get("HealthCondition"));
				pd.putDataValue("Industry", commonmap.get("Industry"));
				pd.putDataValue("Province", commonmap.get("Province"));
				pd.putDataValue("City", commonmap.get("City"));
				pd.putDataValue("Coutry", commonmap.get("Coutry"));
			}else{
				ResponseData.fail();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-edit",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editRecord(@RequestBody PersonRecord record){
		ResponseData pd = null;
		try {
			if(record != null){
				if(personRecordService.editRecord(record)){
					pd = ResponseData.ok();
				}else{
					pd = ResponseData.fail();
				}
			}else{
				pd = ResponseData.fail();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 更改档案状态
	 * @param record
	 * @return
	 */
	@RequestMapping(value="/inter-status",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editRecordStatus(@RequestBody PersonRecord record){
		ResponseData pd = null;
		try {
			if(record != null){
				if(personRecordService.editRecordStatus(record)){
					pd = ResponseData.ok();
				}else{
					pd = ResponseData.fail();
				}
			}else{
				pd = ResponseData.fail();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 通过身份证号或者姓名查询本机构或下属档案
	 * @return
	 */
	@RequestMapping(value="/inter-serachoftj",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchRecordsByTj(@RequestBody Map<String,String> map,HttpServletRequest request){
		ResponseData pd = null;
		try {
			String tj = map.get("tj");
			if(tj==null || tj.equals("")){
				pd = ResponseData.custom("查询条件不能为空");
			}else{
				User user = JWT.findUserByToken(request);
				List<PersonRecord> records = personRecordService.searchRecords(tj, user);
				pd = ResponseData.ok();
				pd.putDataValue("records", records);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 通过身份证号或者姓名查询本机构或下属档案
	 * @return
	 */
	@RequestMapping(value="/inter-searchPerson",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchRecordsByCond(PageParam param, HttpServletRequest request) throws Exception{
		System.out.println(param.getLimit());
		System.out.println(param.getPage());
		System.out.println(param.getParams().get("conds"));
		
		return personRecordService.selectRecordsByConds(param.getLimit(), param.getPage(), param.getParams().get("conds"));
	}
	
	/**
	 * 通过身份证号或者姓名查询本机构或下属档案
	 * @return
	 */
	@RequestMapping(value="/inter-searchPersonOfFam",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchPersonOfFam(PageParam param, HttpServletRequest request) throws Exception{
		System.out.println(param.getLimit());
		System.out.println(param.getPage());
		System.out.println(param.getParams().get("conds"));
		
		return personRecordService.selectRecordsByCondsOfFam(param.getLimit(), param.getPage(), param.getParams().get("conds"));
	}
	
	@RequestMapping(value="/inter-searchOfReceive",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchUsersOfReceive(PageParam param) throws Exception{
		return personRecordService.searchUsersOfReceive(param.getPage(),param.getLimit(), param.getParams().get("conds"));
	}

	@RequestMapping(value="/inter-searchOfReceiveWithIdcard",method=RequestMethod.GET)
	@ResponseBody
	public List<PersonRecord> searchUsersOfReceiveWithIdcard(String keywords) throws Exception{
		return personRecordService.searchUsersOfReceive(keywords);
	}

	@RequestMapping(value="/inter-searchFriendTel",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData searchFriendTel(String recordid) throws Exception{
		return personRecordService.searchFriendTel(recordid);
	}

	@RequestMapping(value="/inter-addFriendTel",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData addFriendTel(@RequestBody FriendTel friendTel) throws Exception{
		return personRecordService.addFriendTel(friendTel);
	}

	@RequestMapping(value="/inter-deleteFriendTel",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData deleteFriendTel(@RequestBody FriendTel friendTel) throws Exception{
		return personRecordService.deleteFriendTel(friendTel);
	}

}
